package ru.task;

import org.json.simple.JSONObject;
import org.json.simple.JSONArray;
import org.json.simple.parser.JSONParser;
import java.io.FileReader;
import java.util.List;
import java.util.ArrayList;

public class JsonSimpleParser {

	private static final String ARR_TICKETS = "tickets";
	private static final String ORIGIN = "origin";
    private static final String ORIGIN_NAME = "origin_name";
    private static final String DESTINATION = "destination";
    private static final String DESTINATION_NAME = "destination_name";
    private static final String DESTINATION_DATE = "departure_date";
    private static final String DEPARTURE_TIME = "departure_time";
    private static final String ARRIVAL_DATE = "arrival_date";
    private static final String ARRIVAL_TIME = "arrival_time";
    private static final String CARRIER = "carrier";
    private static final String STOPS = "stops";
	private static final String PRICE = "price";


	public Root parse() {

		Root root = new Root();
		JSONParser parser = new JSONParser();
		try(FileReader reader = new FileReader("tickets.json")) {

			JSONObject rootJsonObject = (JSONObject)parser.parse(reader);
			JSONArray ticketsJsonArray = (JSONArray)rootJsonObject.get(ARR_TICKETS);

			List<Ticket> ticketsList = new ArrayList<>();
 			for(Object item: ticketsJsonArray) {
				JSONObject ticketJsonObject = (JSONObject)item;

				String origin = (String)ticketJsonObject.get(ORIGIN);
				String origin_name = (String)ticketJsonObject.get(ORIGIN_NAME);
				String destination = (String)ticketJsonObject.get(DESTINATION);
				String destination_name = (String)ticketJsonObject.get(DESTINATION_NAME);
				String departure_date = (String)ticketJsonObject.get(DESTINATION_DATE);
				String departure_time = (String)ticketJsonObject.get(DEPARTURE_TIME);
				String arrival_date = (String)ticketJsonObject.get(ARRIVAL_DATE);
				String arrival_time = (String)ticketJsonObject.get(ARRIVAL_TIME);
				String carrier = (String)ticketJsonObject.get(CARRIER);
				long stops = (Long)ticketJsonObject.get(STOPS);
				long price = (Long)ticketJsonObject.get(PRICE);

				Ticket ticket = new Ticket(origin, origin_name, destination, destination_name, 
					departure_date, departure_time, arrival_date, arrival_time, carrier, 
					(int)stops, (int)price);
				ticketsList.add(ticket);
			}
			root.setTickets(ticketsList);

		
		} catch (Exception e) {
			System.out.println("error " + e.toString());
		}

		//System.out.println("in Json Simple Parser");
		return root;
	}
}
